package com.qdu.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.qdu.commons.RedisKey;
import com.qdu.commons.Result;
import com.qdu.entity.Mytrace;
import com.qdu.entity.RouteTrace;
import com.qdu.entity.User;
import com.qdu.service.IRouteTraceService;
import com.qdu.service.impl.RouteTraceServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/routeTrace")
public class RouteTraceController {
    @Autowired
    RouteTraceServiceImpl routeTraceService;

    @Autowired
    RedisTemplate redisTemplate;


    @PostMapping("/addTrace")
    @ApiOperation(value = "将路线信息添加到数据库中")
    public void addTrace(@RequestBody List<RouteTrace> RouteTrace){
        routeTraceService.saveBatch(RouteTrace);
    }

    @GetMapping("/getTracebyRouteId")
    @ApiOperation(value = "得到轨迹信息")
    public Result getTraceByRouteId(int routeId){
        //先从redis获取
        if (redisTemplate.hasKey(RedisKey.ROUTE_TRACE+routeId)){
            log.info("从redis获取规划的路线");
            List<RouteTrace> routeTraces = redisTemplate.opsForList().range(RedisKey.ROUTE_TRACE+routeId, 0, -1);
            return Result.SUCCESS(routeTraces);
        }

        List<RouteTrace> routeTraces  = routeTraceService.list(new QueryWrapper<RouteTrace>().eq("routeId",routeId).orderByAsc("routeTraceId"));
        if (routeTraces.size()==0){
            return Result.FAIL("暂无路线轨迹");
        }
        if (redisTemplate.hasKey(RedisKey.ROUTE_TRACE+routeId)) redisTemplate.delete(RedisKey.ROUTE_TRACE+routeId);
        redisTemplate.opsForList().rightPushAll(RedisKey.ROUTE_TRACE+routeId, routeTraces);
        return Result.SUCCESS(routeTraces);
    }
}
